<?php
/*
 * Copyright (c) 2023. ogg. Inc. All Rights Reserved.
 * ogg sit down and start building bugs in sunny weather.
 * Author: Ogg <baoziyoo@gmail.com>.
 * LastChangeTime: 2023-02-07 04:16:19
 * ChangeTime: 2023-04-26 10:21:24
 */

declare(strict_types=1);

namespace App\Exception\Handler;

//use App\Core\Biz\Container\Biz;
use App\Enum\ResponseStatusEnum;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Codec\Json;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ErrorExceptionHandler extends ExceptionHandler
{
    protected RequestInterface $request;

//    protected Biz $biz;

    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
//        $this->biz = $biz;
    }

    public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
    {
        $responseData = [
            'code' => $throwable->getCode(),
            'message' => $throwable->getMessage(),
            'data' => null,
            'time' => time(),
        ];
        var_dump($responseData);
        $data = Json::encode($responseData);

        $this->stopPropagation();

        $status = substr((string)$throwable->getCode(), 0, 3);
        $status = $status <= 0 ? 500 : (int)$status;

        return $response->withAddedHeader('Content-Type', 'application/json')->withBody(new SwooleStream($data));


        //return $response->withStatus($status)->withAddedHeader('Content-Type', 'application/json')->withBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
